package com.qd.p2p.web.action;

import java.io.IOException;
import java.text.MessageFormat;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;

import com.qd.p2p.sina.pay.enums.PayType;
import com.qdlc.p2p.biz.processor.TaskProcessorHelper;
import com.qdlc.p2p.biz.processor.event.QuickPayValueEvent;
import com.qdlc.p2p.biz.processor.task.QuickPayTaskProcessor;
import com.qdlc.p2p.biz.service.AccountRechargeService;
import com.qdlc.p2p.biz.util.NotifyRequestHandler;
import com.qdlc.p2p.biz.util.NotifyRequestUrl;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.RechargeStatus;
import com.qdlc.p2p.common.core.queue.ITaskProcessor;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.dal.dto.AccountRecharge;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AccountRechargeModel;

/**
 * 快捷支付通知处理（新浪）
 * @author linya 2016-01-25
 */
public class QuickPayNotifyAction extends BaseAction<AccountRechargeModel>{

	private static final Logger log = Logger.getLogger(QuickPayNotifyAction.class);
	
    @Resource
	AccountRechargeService accountRechargeService;
	
    @SuppressWarnings("static-access")
	@Action(value = NotifyRequestUrl.QUICK_PAY_NOTIFY_ACTION)
	public void quickPayNofify(){
    	
    	log.info("++++ [新浪回调][快捷支付]收到新浪快捷支付回调请求.");
    	
    	NotifyRequestHandler notifyRequest = NotifyRequestHandler.build(getRequest());
    	boolean result = notifyRequest.checkSign();
    	if(!result){
    		log.info("++++ [新浪回调][快捷支付]验签失败!");
    		write("sina error!");
    		return;
    	}
    	
    	//充值订单号
    	String orderNo = notifyRequest.getParam("outer_trade_no");
    	//充值状态
    	String depositStatus = notifyRequest.getParam("deposit_status");
    	//充值金额
    	double depositAmount = notifyRequest.getDoubleParam("deposit_amount");
    	//错误信息
    	String errorMessage = notifyRequest.getParam("error_message");
    	
    	AccountRecharge recharge = accountRechargeService.getRechargeByOrder(orderNo);
    	
    	//如果recharge为空，等待0.3s，重新尝试获取数据
    	if(recharge == null){
    		try {
				Thread.currentThread().sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    		recharge = accountRechargeService.getRechargeByOrder(orderNo);
    		if(recharge == null){
    			log.info("++++ [新浪回调][快捷支付]数据库表qd_account_recharge中没有找到充值订单号:" + orderNo);
    			write("no order_no error!");
    			return; 
    		}
    	}
    	
    	if(recharge.getStatus() == AccountRechargeModel.RECHARGE_SUCCESS){
    		log.info("++++ [新浪回调][快捷支付]订单号:" + orderNo + "已经成功处理过了!");
    		write("success");
    		return;
    	}
    	
    	User user = recharge.getUser();
    	
    	log.info(MessageFormat.format("++++ [新浪回调][快捷支付]用户:{0},订单号:{1},状态:{2}!", user, orderNo, depositStatus));

    	RechargeStatus rechargeStatus = RechargeStatus.getStatus(depositStatus);
    	//回调状态成功或失败都需要写入数据库，更新状态
    	if(RechargeStatus.SUCCESS == rechargeStatus || RechargeStatus.FAILED == rechargeStatus){
    		QuickPayValueEvent event = new QuickPayValueEvent();
    		event.setOrderId(orderNo);
    		event.setUser(user);
    		event.setMoney(depositAmount);
    		event.setPayType(PayType.binding_pay.getType());
    		event.setStatus(rechargeStatus);
    		event.setErrorMessage(errorMessage);
    		event.setAccountRecharge(recharge);
    		
    		ITaskProcessor taskProcessor = TaskProcessorHelper.getProcessor(QuickPayTaskProcessor.class);
    		try {
				taskProcessor.transactionProcesss(event);
				write("success");
			} catch (TaskProcessorException e) {
				log.info(MessageFormat.format("++++ [新浪回调][快捷支付]用户:{0},订单号:{1},处理快捷支付回调异常!", user, orderNo));
				e.printStackTrace();
				write("exception error!");
			}
    	}else{
    		log.info("++++ [新浪回调][快捷支付]回调状态错误，状态:" + depositStatus);
    		write("status error!");
    	}
    	
    }
    
    private void write(String message){
    	try {
			response.getWriter().print(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}
